import {aliOssSecurityToken} from "@/api/file"
import crypto from 'crypto-js';
import { Base64 } from 'js-base64';
import AliOssSdk from "ali-oss";

// 计算签名。
function computeSignature(accessKeySecret, canonicalString) {
    return crypto.enc.Base64.stringify(crypto.HmacSHA1(canonicalString, accessKeySecret));
}

const date = new Date();
date.setHours(date.getHours() + 1);
const policyText = {
    expiration: date.toISOString(), // 设置policy过期时间。
    conditions: [
        // 限制上传大小。
        ["content-length-range", 0, 1024 * 1024 * 1024],
    ],
};
export const getFormDataParams =async ()=> {
    const {data} = await aliOssSecurityToken()
    const policy = Base64.encode(JSON.stringify(policyText)) // policy必须为base64的string。
    console.log("policy", policy)
    const signature = computeSignature(data.accessKeySecret, policy)
    console.log("signature", signature)
    const formData = {
        OSSAccessKeyId: data.accessKeyId,
        signature,
        policy,
        'x-oss-security-token': data.securityToken
    }
    return formData
}
export const signatureUrl = async ObjName => {
    const client = await getClientOss();
    return await client.signatureUrl(`${ObjName}`);
};
const getAuth = () => {
    // eslint-disable-next-line no-async-promise-executor
    return new Promise(async (resolve, reject) => {
        try {
            const { data } = await aliOssSecurityToken();
            resolve({
                region: "oss-cn-hangzhou",
                authorizationV4: true,
                bucket: data.bucketName,
                accessKeyId: data.accessKeyId,
                accessKeySecret: data.accessKeySecret,
                stsToken: data.securityToken
            });
        } catch (err) {
            reject(err);
        }
    });
};
const getClientOss = () => {
    // eslint-disable-next-line no-async-promise-executor
    return new Promise(async (resolve, reject) => {
        try {
            const clientOss = await getAuth();
            const clientOssObj = new AliOssSdk({
                ...clientOss
            });
            resolve(clientOssObj);
        } catch (err) {
            reject(err);
        }
    });
};

/**
 * 时间戳
 */
export const getCurrentTime = () => {
    return new Date().valueOf();
};
/**
 * 4位随机数
 * @return {number}
 */
export const getRandom = () => {
    return Math.floor(Math.random() * 10000);
};
/**
 * 获取文件后缀
 */
export const getSuffix = fileName => {
    return fileName.slice(fileName.lastIndexOf(".") + 1);
};
